#!/usr/bin/env python3
# -*- coding: utf-8 -*-


from envelopes import Envelope
import requests
import datetime

import re

rx = re.compile(r'(201708010(\d+) ?(\w+))|((信计)?(20)?17\d+ ?\w+\d*)')

user = '281124072@qq.com'
password = 'iezimtkqmcjlbgij'

appid = "a867675e7027ffd19182490351e6852e"
url = "https://api.ownthink.com/bot"

def get_reply(spoken):
    req = requests.get(url, params={'appid': appid, 'spoken': spoken, 'userid':'FreakWill'})
    a = req.json()
    if a['message']=='success':
        return a['data']['info']['text']
    else:
        return 'fail to request'


def op(body, mail):
    if body:
        try:
            reply = get_reply(body)
        except:
            reply = '看不懂，说人话'
    else:
        reply = '测试回信，请不要理会'
    envelope = Envelope(from_addr=(user, 'From William Song'),
        to_addr=(mail, 'To you'), subject='回复', text_body=reply)
    envelope.add_attachment('mailtest.py')
    envelope.send('smtp.qq.com', login=user, password=password, tls=True)


# -------------- 信件操作 ---------------
def load(attachments):
    for attachment in message.attachments:
        with open('homework17/' + attachment['filename'], 'w') as fo:
            s = fo.write(str(attachment['content']))

def reply(body, mail):
    envelope = Envelope(from_addr=(user, 'From William Song'),
        to_addr=(mail, 'To you'), subject='回复', text_body=body)
    envelope.add_attachment('mailtest.py')
    envelope.send('smtp.qq.com', login=user, password=password, tls=True)

# -------- 收信 ---------
from imbox import Imbox

with Imbox('imap.qq.com',
        username='281124072@qq.com',
        password='iezimtkqmcjlbgij',
        ssl=True, starttls=False) as imbox:

    # Unread messages
    inbox_messages = imbox.messages(unread=True)

    for uid, message in inbox_messages:
        # if rx.match(message.subject):  # 正则表达式过滤（没有必要）
        #     print('主题：', message.subject)
        #     print('发信人邮箱：', message.sent_from[0]['email'])
        #     print('收信人邮箱：', message.sent_to[0]['email'])
        #     print('正文：', message.body['plain'])
        # if message.subject.startswith('x'):

        if message.sent_from[0]['email'] == '240107654@qq.com':
            # if message.subject.startswith('x'):
            print('删除一条来自 %s 的邮件' % message.sent_from[0]['name'])
            imbox.delete(uid)

        #     print('收到<%s>来信' % message.subject)
        #     mail = message.sent_from[0]['email']
        #     if 'qq' in mail:
        #         print('给<%s>写回信' % message.subject)
        #         # print(message.body)
        #         load(message.attachments)
        #         if message.body['plain']:
        #             op(message.body['plain'][0], mail)
        #         else:
        #             op('你好', mail)
            # imbox.mark_seen(uid)

